// 全局守卫
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';

import { JwtTool } from '@/utils/tool';

@Injectable()
export class JwtGuard extends AuthGuard('jwt') {
  private jwt = new JwtTool();

  constructor(private reflector: Reflector) {
    super();
  }

  canActivate(context: ExecutionContext): boolean {
    try {
      const isPass = this.reflector.get<boolean>(
        'jwtPass',
        context.getHandler(),
      );
      if (isPass) return true;

      const request = context.switchToHttp().getRequest();
      const token = this.extractTokenFromHeader(request);

      if (!token) {
        throw new UnauthorizedException('请登录');
        // throw new (request as any).customException('请登录', 401);
      }

      const decoded = this.jwt.verifyToken(token);

      request.user = decoded;

      // const url = request.url;
      // if (url.startsWith('/api')) {
      //   return true;
      // }

      return true;
    } catch {
      throw new UnauthorizedException('无效 token');
    }
  }

  private extractTokenFromHeader(request: any): string | undefined {
    const authorization = request.headers.authorization ?? '';
    const token = authorization.trim().replace(/Bearer\s+/i, '');
    return authorization ? token : undefined;
  }
}

/**
 * @UseGuards()  // 不使用守卫，允许访问
 * @UseGuards(LocalAuthGuard) // 仅对这个路由使用本地认证，绕过 JWT 验证
 */
